package com.msh.automatic.android.control.service

import android.accessibilityservice.AccessibilityService
import android.accessibilityservice.AccessibilityServiceInfo
import android.content.Context
import android.os.PowerManager
import android.util.Log
import android.view.accessibility.AccessibilityEvent
import android.view.accessibility.AccessibilityNodeInfo
import cn.hutool.core.util.StrUtil
import com.alibaba.fastjson2.JSON

class AIAccessibilityService : AccessibilityService() {

    var currentPackage = ""
    var currentActivity = ""
    private var currentRootNode:AccessibilityNodeInfo? = null

    companion object {
        var isInit:Boolean = false
        lateinit var aiAccessibilityService:AIAccessibilityService
        val TAG = "AIAccessibilityService"
    }

    fun getCurrentRootNode():AccessibilityNodeInfo{
        this.rootInActiveWindow?.let {
            this.currentRootNode = it
            return it
        }
        return this.currentRootNode!!
    }

    override fun onServiceConnected() {
        super.onServiceConnected()
        // 可选初始化逻辑
        Log.d(TAG, "服务已连接")
        aiAccessibilityService = this
        isInit = true
    }

    override fun onAccessibilityEvent(event: AccessibilityEvent) {
        Log.d(TAG, "onAccessibilityEvent: ${event.eventType} ${event.action} ${event.contentChangeTypes} ${event.contentDescription} ${JSON.toJSONString(event.text)} ")
        if (event.eventType == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED && event.contentChangeTypes == AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED) {
            var eventPackageName = event.packageName?.toString()!!
            var className = event.className?.toString()!!
            // 排除系统视图类名
            if (!className.contains(".") || className.startsWith("android.")) {
                return
            }
            val rootInActiveWindow = this.rootInActiveWindow ?: return
            val packageName = rootInActiveWindow.packageName?: return
            if(!StrUtil.equals(eventPackageName,packageName.toString())){
                return
            }
            currentPackage = packageName.toString()
            currentActivity = className
            this.rootInActiveWindow?.let {
                this.currentRootNode=it
            }
            Log.d(TAG, "当前Activity: $currentPackage / $currentActivity")
        }
    }

    override fun onInterrupt() {
        Log.d(TAG, "服务中断")
    }
}
